package com.dingwen.spsest.handler;

import cn.hutool.http.HttpStatus;
import com.dingwen.spsest.exception.ValidateCodeException;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义认证失败处理
 *
 * @author dingwen
 * 2021.05.20 09:24
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    /**
     * 在身份验证失败
     *
     * @param httpServletRequest  http servlet请求
     * @param httpServletResponse http servlet响应
     * @param e                   e
     * @throws IOException      io exception
     * @throws ServletException servlet异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        String msg = "";
        // 验证码自定义异常的处理
        if (e instanceof ValidateCodeException) {
            msg = e.getMessage();
        } else if (e instanceof LockedException) {
            msg = "账户被锁定请联系管理员!";
        } else if (e instanceof CredentialsExpiredException) {
            msg = "密码过期请联系管理员!";
        } else if (e instanceof AccountExpiredException) {
            msg = "账户过期请联系管理员!";
        } else if (e instanceof DisabledException) {
            msg = "账户被禁用请联系管理员!";
        } else if (e instanceof BadCredentialsException) {
            msg = "用户名或密码输入错误,请重新输入!!";
        }
        PrintWriter printWriter = httpServletResponse.getWriter();
        printWriter.write(msg);
        printWriter.flush();
        printWriter.close();

    }
}
